/*
	xaoi 230601
*/

var xaoi = {};

xaoi.time = function(o){
	var t = o||new Date();
	return parseInt(t.getTime()/1000);
}

xaoi.date = function(str){
	var t;
	switch(arguments.length){
		case 1:
			t = new Date();
		break;
		case 2:
			if(Object.prototype.toString.call(arguments[1]) === '[object Date]'){
				t = arguments[1];
			}else if(typeof arguments[1] === 'number' && arguments[1].toString().length > 10){
				t = new Date(arguments[1]);
			}else if(arguments[1] >= 0){
				t = new Date(parseInt(arguments[1]+'000'));
			}else if(arguments[1] < 0){
				t = Math.abs(arguments[1]);
				var d = parseInt(t / 60 / 60 / 24);
				var H = parseInt(t / 60 / 60 % 24);
				var i = parseInt(t / 60 % 60);
				var s = parseInt(t % 60);
				str = str.replace(/d([^dHis]*)/g,d > 0?d+'$1':'');
				str = str.replace(/H([^dHis]*)/g,H > 0?H+'$1':d>0?'0':'');
				str = str.replace(/i([^dHis]*)/g,i > 0?i+'$1':d>0 || H>0?'0':'');
				str = str.replace(/s([^dHis]*)/g,s > 0?s+'$1':d>0 || H>0 || i>0?'0':'');
				return str;
			}else{
				return '';
			}
		break;
	}
	var Y = t.getFullYear();
	var y = t.getFullYear().toString().substr(2);
	var m = t.getMonth()+1;
	var d = t.getDate();
	var H = t.getHours();
	var i = t.getMinutes();
	var s = t.getSeconds();
	if(m < 10)m = '0'+m;
	if(d < 10)d = '0'+d;
	if(H < 10)H = '0'+H;
	if(i < 10)i = '0'+i;
	if(s < 10)s = '0'+s;
	str = str.replace(/Y/g,Y);
	str = str.replace(/y/g,y);
	str = str.replace(/m/g,m);
	str = str.replace(/d/g,d);
	str = str.replace(/H/g,H);
	str = str.replace(/i/g,i);
	str = str.replace(/s/g,s);
	return str;
}

xaoi.strtotime = function(str){
	if(!str)return 0
    var _arr = str.split(' ');
    var _day = _arr[0].split('-');
    _arr[1] = (_arr[1] == null) ? '0:0:0' :_arr[1];
    var _time = _arr[1].split(':');
    for (var i = _day.length - 1; i >= 0; i--) {
        _day[i] = isNaN(parseInt(_day[i])) ? 0 :parseInt(_day[i]);
    };
    for (var i = _time.length - 1; i >= 0; i--) {
        _time[i] = isNaN(parseInt(_time[i])) ? 0 :parseInt(_time[i]);
    };
    var _temp = new Date(_day[0],_day[1]-1,_day[2],_time[0],_time[1],_time[2]);
    return _temp.getTime() / 1000;
}

/*
	element 表单验证,注意prop必填，不然有坑，不要用v-else
	dom
		<el-form ref="edit" :model="form" label-width="80px">
			<el-form-item label="名称" prop="name" :rules="rule('请输入名称')">
				<el-input v-model="form.name" maxlength="20" placeholder="请输入名称"></el-input>
			</el-form-item>
		</el-form>
		
	data
		return {
			form:{},
			rule:xaoi.rule(this,'edit')
		}

	submit
		if(!await this.rule())return;

	单独验证
		if(!await this.rule({
			phone(){

			},
			password(){

			},
		}))return;

	显示错误
		this.rule.log.name = res.msg
*/
xaoi.rule = function(vue,ref,lis){

	lis = lis || {};

	var temp = {};

	var logs = {};

	var fn = function(){
		switch(arguments.length){
			case 0:
				return new Promise(function(ok){vue.$refs[ref].validate(ok)});
			break;
			case 1:
				if(arguments[0] === null){
					return new Promise(function(ok){
						if(vue.$refs[ref])vue.$refs[ref].clearValidate();
						vue.$nextTick(ok)
					});
				}
				if(typeof arguments[0] === 'object'){
					temp = arguments[0];
					return new Promise(function(ok){
						var fns = [];
						for(var i in temp){
							fns.push([i,temp[i]])
						}
						var r_ok = true;
						var f3 = function(){
							var ite = fns.pop();
							if(ite){
								vue.$refs[ref].validateField(ite[0],function(msg,lis){
									if(lis === null){

									}else{
										r_ok = false;
									}
									f3()
								})
							}else{
								temp = {}
								ok(r_ok)
							}
						}
						f3();
					})
				}
				var type = 'default';
				var msg = arguments[0];
				break;
			case 2:
				var type = arguments[0];
				var msg = arguments[1];
			break;
		}
		
		var rule = [];
		switch(type){
			case 'default':
				if(msg)rule.push({ required: true, message: msg, trigger: 'blur' });
			break;
		}
		rule.push({
			validator:function(d, value, callback){
				if(typeof logs[d.field] === 'undefined')logs[d.field] = '';
				if(typeof fn.log[d.field] === 'undefined')
				Object.defineProperty(fn.log, d.field, {
					enumerable:true,
					configurable:true,
					get:function(){
						return logs[d.field];
					},
					set:function(val){
						logs[d.field] = val;
						vue.$refs[ref].validateField(d.field)
					}
				})

				var f2 = function(){
					if(logs[d.field])callback(logs[d.field]);else callback();
					logs[d.field] = '';
				}

				var f = function(){
					if(typeof temp[d.field] !== 'undefined'){
						if(!logs[d.field])logs[d.field] = temp[d.field].call(vue,value);
						Promise.resolve(logs[d.field]).then(function(v){
							logs[d.field] = v;
							f2();
						})
					}else{
						f2();
					}
				}

				if(typeof lis[d.field] !== 'undefined'){
					if(!logs[d.field])logs[d.field] = lis[d.field].call(vue,value);
					Promise.resolve(logs[d.field]).then(function(v){
						logs[d.field] = v;
						f();
					})
				}else{
					f();
				}
			},
			trigger: 'blur'
		})
		return rule
	}

	fn.log = {}

	return fn;
}

//拦截器
xaoi.call = function(){

	function object_clone(o){
		if(Object.prototype.toString.call(o) === '[object Object]'){
			var n = {};
			for(var i in o)n[i] = object_clone(o[i]);
			return n;
		}else if(Object.prototype.toString.call(o) === '[object Array]'){
			var n = [];
			for(var i = 0,s = o.length;i!==s;++i)n.push(object_clone(o[i]));
			return n;
		}else{
			return o;
		}
	}

	var fn = function(){
		var args = [];
		for(var i in arguments)args.push(arguments[i]);

		var that = object_clone(this);
		if(args.length && typeof args[0] === 'function'){
			that.req.push(args[0])
			if(args.length >= 2 && typeof args[1] === 'function')that.res.push(args[1]);
			return fn.bind(that)
		}else{
			that.args = args;
			var f = function(d,h){
				if(d.length){
					var p = d.splice(0,1)[0].apply(that,that.args)
					Promise.resolve(p).then(function(x){
						typeof x !== 'undefined'?h(x):f(d,h)
					}).catch(h)
				}else{
					h.apply(that,that.args)
				}
			}
			return new Promise(function(ok){
				f(that.req,function(d){
					that.args = [d];
					f(that.res,function(d){
						ok(d)
					})
				});
			})
		}
	}

	return fn.bind({req:[],res:[]});
}()


/*
	Vue.prototype.$post = xaoi.ajax(function(){
		this.req.url = '?action=' + this.req.url;
	},d=>{
		if(d.code === 0){
			return d.data
		}else{
			Vue.prototype.$message.error(d.message)
		}
	})
 */
xaoi.ajax = xaoi.call(function(url,data,handle){
	var req = {
		method:'post',
		url:url,
		params:'',
		data:data,
		headers:{},
		handle:handle,
		withCredentials:false,
	}

	this.req = req;

	this.http = function(req){
		
		return new Promise(function(ok){
			var xhr = new XMLHttpRequest();
			xhr.open(req.method,req.url);
			for(var i in req.headers)xhr.setRequestHeader(i,req.headers[i]);
			xhr.addEventListener('load',function(){
				if(xhr.readyState==4){
					if(xhr.status==200){
						var t
						try{
							t=JSON.parse(xhr.responseText);
						}catch(ex){
							ok({data:{code:500}});
							return;
						}
						ok({data:t});
					}else{
						ok({data:{code:404}});
					}
				}
			});
			if(Object.prototype.toString.call(req.data) === '[object Object]'){
				xhr.setRequestHeader('Content-Type','application/json');
				req.data = JSON.stringify(req.data)
			}
			xhr.send(req.data);
		})
	}
},function(){
	var that = this;
	return new Promise(function(ok){
		
		var onhandle = function(data){
			if(typeof that.req.handle == 'function'){
				Promise.resolve(that.req.handle.call(that,data)).then(function(d){
					if(d){
						that.args = [d]
						ok()
					}
				})
			}else{
				that.args = [data]
				ok()
			}
		}

		that.http(that.req).then(function(res){
			if(typeof res.data === 'string'){
				onhandle({code:404,data:res.data,message:'请求失败'})
			}else{
				if(Array.isArray(res.data)){
					res.data = {
						code:res.data.length?res.data[0]:0,
						data:res.data.length>1?res.data[1]:null,
						message:res.data.length>2?res.data[2]:null,
					}
				}
	
				that.res = res;
	
				onhandle(res.data)
			}
		},function(error){
			console.error(error)
			onhandle({code:404,data:error,message:'请求失败'})
		})
	})
})

/**
 * 延时等待
 * 创建
 * 	var onok = xaoi.ele()
 * 
 * 添加监听
 * 	await onok()
 * 
 * 执行ok
 * 	onok(1)
 * @returns function
 */
xaoi.ele = function(){
	var is_ok = false;
	var lis = [];
	var _d;
	return function(d){
		if(arguments.length){
			_d = d
			is_ok = true;
			for(var i in lis)lis[i](_d);
			lis = []
		}else{
			return new Promise(function(ok){
				if(is_ok){
					ok(_d);
				}else{
					lis.push(ok)
				}
			})
		}
	}
}

xaoi.session = function(){
	switch(arguments.length){
		case 1:
			var r = sessionStorage.getItem((xaoi.session.prefix||'')+arguments[0]);
			return r?JSON.parse(r):r;
		break;
		case 2:
			if(arguments[1] === null){
				sessionStorage.removeItem((xaoi.session.prefix||'')+arguments[0]);
			}else{
				sessionStorage.setItem((xaoi.session.prefix||'')+arguments[0],JSON.stringify(arguments[1]))
			}
		break;
	}
}

xaoi.store = function(){
	switch(arguments.length){
		case 1:
			var r = localStorage.getItem((xaoi.store.prefix||'')+arguments[0]);
			return r?JSON.parse(r):r;
		break;
		case 2:
			if(arguments[1] === null){
				localStorage.removeItem((xaoi.store.prefix||'')+arguments[0]);
			}else{
				localStorage.setItem((xaoi.store.prefix||'')+arguments[0],JSON.stringify(arguments[1]))
			}
		break;
	}
}

xaoi.ws = function(url){
	var ws;
	var fn = function(){
		ws = new WebSocket(url);
		ws.onopen = function(e){
			if(typeof fn.onopen === 'function')fn.onopen(e)
		};
		ws.onmessage = function(e){
			var d;
			try{d=JSON.parse(e.data);}catch(e){};
			if(d && typeof d[0] !== 'undefined'){
				var k = d.shift();
				if(typeof fn[k] === 'function')fn[k].apply(null,d)
			}
		};
		ws.onerror = function(e){
			if(typeof fn.onerror === 'function')fn.onerror(e)
		};
		ws.onclose = function(e){
			if(typeof fn.onclose === 'function')fn.onclose(e)
		};

		fn.send = function(){
			var args = [];
			for(var i in arguments)args.push(arguments[i]);
			if(ws.readyState === 1)
				ws.send(JSON.stringify(args));
			else
				console.log('连接断开，请刷新页面再试！');
		};

		fn.close = function(){
			ws.close();
		};
	}
	
	return fn;
};

/**
 * 发送事件
 * xaoi.event('add',{})
 * 
 * 接收事件
 * var index = xaoi.event.on('add',d=>{})
 * var index = xaoi.event.on(['add','edit'],d=>{})
 * 
 * 取消接收事件
 */
xaoi.event = function(){
	var Store = {};
	var unevent = function(){
		if(typeof Store[this._uid] !== 'undefined'){
			delete Store[this._uid]
		}
	}
	return function(vue){
		if(typeof vue === 'string' || Array.isArray(vue)){
			var args = [];
			for(var i = 0;i!==arguments.length;++i)args.push(arguments[i])
			return new Promise(function(ok){
				var name = args.shift();
				var all = [];
				if(name)
				for(var i in Store){
					if(typeof Store[i][name] !== 'undefined'){
						for(var i in Store[i][name]){
							all.push(Promise.resolve(Store[i][name][i].apply({},args)))
						}
					}
				}
				Promise.all(all).then(ok)
			})
		}else{
			var destroyed = vue.$options.destroyed
			if(!destroyed.includes(unevent))destroyed.push(unevent)
			var uid = vue._uid
			Store[uid] = {};
			return function(name,fn){
				if(typeof Store[uid][name] === 'undefined')Store[uid][name] = [];
				var lis = Store[uid][name];
				lis.push(fn)
				return function(){
					lis.splice(lis.findIndex(function(v){return v === fn}),1)
				}
			}
		}
	}
}();


/**
 * 判断节点是否显示
 * @param {dom} a 父节点，必须定位
 * @param {*} b 显示的节点
 * @param {*} c 回调事件
 * @returns 
 */
 xaoi.is_show = function(a,b,c){
	var fn = function(){
		c(b.offsetTop + b.offsetHeight > a.scrollTop && b.offsetTop < a.scrollTop + a.clientHeight);
	};
	a.addEventListener('scroll',fn)
	return {
		close:function(){
			a.removeEventListener('scroll',fn)
		}
	};
}

xaoi.import = function(){

	var head = document.getElementsByTagName('head')[0];

	var is_es6 = function(){
		try{
			(new Function('var fn = async function(){}')).call()
			return true;
		}catch(e){
			!function n(t,e,r){function o(u,f){if(!e[u]){if(!t[u]){var c="function"==typeof require&&require;if(!f&&c)return c(u,!0);if(i)return i(u,!0);var s=new Error("Cannot find module '"+u+"'");throw s.code="MODULE_NOT_FOUND",s}var l=e[u]={exports:{}};t[u][0].call(l.exports,function(n){var e=t[u][1][n];return o(e?e:n)},l,l.exports,n,t,e,r)}return e[u].exports}for(var i="function"==typeof require&&require,u=0;u<r.length;u++)o(r[u]);return o}({1:[function(n,t,e){"use strict";function r(){}function o(n){try{return n.then}catch(t){return d=t,w}}function i(n,t){try{return n(t)}catch(e){return d=e,w}}function u(n,t,e){try{n(t,e)}catch(r){return d=r,w}}function f(n){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof n)throw new TypeError("not a function");this._37=0,this._12=null,this._59=[],n!==r&&v(n,this)}function c(n,t,e){return new n.constructor(function(o,i){var u=new f(r);u.then(o,i),s(n,new p(t,e,u))})}function s(n,t){for(;3===n._37;)n=n._12;return 0===n._37?void n._59.push(t):void y(function(){var e=1===n._37?t.onFulfilled:t.onRejected;if(null===e)return void(1===n._37?l(t.promise,n._12):a(t.promise,n._12));var r=i(e,n._12);r===w?a(t.promise,d):l(t.promise,r)})}function l(n,t){if(t===n)return a(n,new TypeError("A promise cannot be resolved with itself."));if(t&&("object"==typeof t||"function"==typeof t)){var e=o(t);if(e===w)return a(n,d);if(e===n.then&&t instanceof f)return n._37=3,n._12=t,void h(n);if("function"==typeof e)return void v(e.bind(t),n)}n._37=1,n._12=t,h(n)}function a(n,t){n._37=2,n._12=t,h(n)}function h(n){for(var t=0;t<n._59.length;t++)s(n,n._59[t]);n._59=null}function p(n,t,e){this.onFulfilled="function"==typeof n?n:null,this.onRejected="function"==typeof t?t:null,this.promise=e}function v(n,t){var e=!1,r=u(n,function(n){e||(e=!0,l(t,n))},function(n){e||(e=!0,a(t,n))});e||r!==w||(e=!0,a(t,d))}var y=n("asap/raw"),d=null,w={};t.exports=f,f._99=r,f.prototype.then=function(n,t){if(this.constructor!==f)return c(this,n,t);var e=new f(r);return s(this,new p(n,t,e)),e}},{"asap/raw":4}],2:[function(n,t,e){"use strict";function r(n){var t=new o(o._99);return t._37=1,t._12=n,t}var o=n("./core.js");t.exports=o;var i=r(!0),u=r(!1),f=r(null),c=r(void 0),s=r(0),l=r("");o.resolve=function(n){if(n instanceof o)return n;if(null===n)return f;if(void 0===n)return c;if(n===!0)return i;if(n===!1)return u;if(0===n)return s;if(""===n)return l;if("object"==typeof n||"function"==typeof n)try{var t=n.then;if("function"==typeof t)return new o(t.bind(n))}catch(e){return new o(function(n,t){t(e)})}return r(n)},o.all=function(n){var t=Array.prototype.slice.call(n);return new o(function(n,e){function r(u,f){if(f&&("object"==typeof f||"function"==typeof f)){if(f instanceof o&&f.then===o.prototype.then){for(;3===f._37;)f=f._12;return 1===f._37?r(u,f._12):(2===f._37&&e(f._12),void f.then(function(n){r(u,n)},e))}var c=f.then;if("function"==typeof c){var s=new o(c.bind(f));return void s.then(function(n){r(u,n)},e)}}t[u]=f,0===--i&&n(t)}if(0===t.length)return n([]);for(var i=t.length,u=0;u<t.length;u++)r(u,t[u])})},o.reject=function(n){return new o(function(t,e){e(n)})},o.race=function(n){return new o(function(t,e){n.forEach(function(n){o.resolve(n).then(t,e)})})},o.prototype["catch"]=function(n){return this.then(null,n)}},{"./core.js":1}],3:[function(n,t,e){"use strict";function r(){if(c.length)throw c.shift()}function o(n){var t;t=f.length?f.pop():new i,t.task=n,u(t)}function i(){this.task=null}var u=n("./raw"),f=[],c=[],s=u.makeRequestCallFromTimer(r);t.exports=o,i.prototype.call=function(){try{this.task.call()}catch(n){o.onerror?o.onerror(n):(c.push(n),s())}finally{this.task=null,f[f.length]=this}}},{"./raw":4}],4:[function(n,t,e){(function(n){"use strict";function e(n){f.length||(u(),c=!0),f[f.length]=n}function r(){for(;s<f.length;){var n=s;if(s+=1,f[n].call(),s>l){for(var t=0,e=f.length-s;e>t;t++)f[t]=f[t+s];f.length-=s,s=0}}f.length=0,s=0,c=!1}function o(n){var t=1,e=new a(n),r=document.createTextNode("");return e.observe(r,{characterData:!0}),function(){t=-t,r.data=t}}function i(n){return function(){function t(){clearTimeout(e),clearInterval(r),n()}var e=setTimeout(t,0),r=setInterval(t,50)}}t.exports=e;var u,f=[],c=!1,s=0,l=1024,a=n.MutationObserver||n.WebKitMutationObserver;u="function"==typeof a?o(r):i(r),e.requestFlush=u,e.makeRequestCallFromTimer=i}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],5:[function(n,t,e){"function"!=typeof Promise.prototype.done&&(Promise.prototype.done=function(n,t){var e=arguments.length?this.then.apply(this,arguments):this;e.then(null,function(n){setTimeout(function(){throw n},0)})})},{}],6:[function(n,t,e){n("asap");"undefined"==typeof Promise&&(Promise=n("./lib/core.js"),n("./lib/es6-extensions.js")),n("./polyfill-done.js")},{"./lib/core.js":1,"./lib/es6-extensions.js":2,"./polyfill-done.js":5,asap:3}]},{},[6]);

			return false;
		}
	}()

	function dec62(n) {
		var base = 62;
		var index = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		var ret = '',a;
		for(var t = Math.floor(Math.log10(n) / Math.log10(base)); t >= 0; t --) {
			a = Math.floor(n / Math.pow(base, t));
			ret += index.substr(a, 1);
			n -= a * Math.pow(base, t);
		}
		return ret;
	}

	function url_path(path){1
		path = path.replace(new RegExp('\\\\','g'),'/');
		var last = '';
		while(path != last){
			last = path;
			path = path.replace(/[^\/]+\/\.\.\//g,'');
		}
		last = '';
		while(path != last){
			last = path;
			path = path.replace(/\.\//g,'');
		}
		return path;
	}
	
	var _config = function(){
		var script = document.scripts[document.scripts.length-1];
		var r = {};
		r.lib = script.getAttribute('lib')||script.src.substr(0,script.src.lastIndexOf('/'))
		r.lib += r.lib.length && r.lib[r.lib.length-1] === '/'?'':'/'
		r.root = script.getAttribute('root')||(location.pathname.substr(0,location.pathname.lastIndexOf('/'))+'/')
		r.root += r.root.length && r.root[r.root.length-1] === '/'?'':'/'
		r.debug = script.hasAttribute('debug')
		r.ws = script.getAttribute('ws')||''
		r.mode = script.getAttribute('mode')||'xhr'
		if(r.ws && !(r.ws.indexOf('ws://') === 0 || r.ws.indexOf('wss://') === 0))r.ws = (location.protocol === 'http:'?'ws://':'wss://')+location.host+r.ws;
		return r;
	}();

	var revue=function(){function d(a,d){if(d.functional){var f=d.render;d.render=function(c,d){var e=b[a].instances;return d&&e.indexOf(d.parent)<0&&e.push(d.parent),f(c,d)}}else e(d,c,function(){var c=b[a];c.Ctor||(c.Ctor=this.constructor),c.instances.push(this)}),e(d,"beforeDestroy",function(){var c=b[a].instances;c.splice(c.indexOf(this),1)})}function e(a,b,c){var d=a[b];a[b]=d?Array.isArray(d)?d.concat(c):[d,c]:[c]}function f(a){return function(b,c){try{a(b,c)}catch(d){console.error(d),console.warn("Something went wrong during Vue component hot-reload. Full reload required.")}}}function g(a,b){var c;for(c in a)c in b||delete a[c];for(c in b)a[c]=b[c]}function h(a){if(a._u){var b=a._u;return a._u=function(a){try{return b(a,!0)}catch(c){return b(a,null,!0)}},function(){a._u=b}}}var a={},b={},c="beforeCreate";return a.createRecord=function(a,c){b[a]||(Ctor=null,"function"==typeof c&&(Ctor=c,c=Ctor.options),d(a,c),b[a]={Ctor:Ctor,options:c,instances:[]})},a.isRecorded=function(a){return"undefined"!=typeof b[a]},a.rerender=f(function(a,c){var e,f,d=b[a];return c?("function"==typeof c&&(c=c.options),d.Ctor?(d.Ctor.options.render=c.render,d.Ctor.options.staticRenderFns=c.staticRenderFns,d.instances.slice().forEach(function(a){a.$options.render=c.render,a.$options.staticRenderFns=c.staticRenderFns,a._staticTrees&&(a._staticTrees=[]),Array.isArray(d.Ctor.options.cached)&&(d.Ctor.options.cached=[]),Array.isArray(a.$options.cached)&&(a.$options.cached=[]);var b=h(a);a.$forceUpdate(),a.$nextTick(b)})):(d.options.render=c.render,d.options.staticRenderFns=c.staticRenderFns,d.options.functional&&(Object.keys(c).length>2?g(d.options,c):(e=d.options._injectStyles,e&&(f=c.render,d.options.render=function(a,b){return e.call(b),f(a,b)})),d.options._Ctor=null,Array.isArray(d.options.cached)&&(d.options.cached=[]),d.instances.slice().forEach(function(a){a.$forceUpdate()}))),void 0):(d.instances.slice().forEach(function(a){a.$forceUpdate()}),void 0)}),a.reload=f(function(a,c){var f,e=b[a];c&&("function"==typeof c&&(c=c.options),d(a,c),e.Ctor?(f=e.Ctor.super.extend(c),f.options._Ctor=e.options._Ctor,e.Ctor.options=f.options,e.Ctor.cid=f.cid,e.Ctor.prototype=f.prototype,f.release&&f.release()):g(e.options,c)),e.instances.slice().forEach(function(a){a.$vnode&&a.$vnode.context?a.$vnode.context.$forceUpdate():console.warn("Root or manually mounted instance modified. Full reload required.")})}),a}();

	var _ws = function(url){
		var ws;
		var fn = function(){
			if(typeof WebSocket === 'undefined')return;
			ws = new WebSocket(url);
			ws.onopen = function(e){
				if(typeof fn.onopen === 'function')fn.onopen(e)
			};
			ws.onmessage = function(e){
				var d;
				try{d=JSON.parse(e.data);}catch(e){};
				if(d && typeof d[0] !== 'undefined'){
					var k = d.shift();
					if(typeof fn[k] === 'function')fn[k].apply(null,d)
				}
			};
			ws.onerror = function(e){
				if(typeof fn.onerror === 'function')fn.onerror(e)
			};
			ws.onclose = function(e){
				if(typeof fn.onclose === 'function')fn.onclose(e)
			};

			fn.send = function(){
				var args = [];
				for(var i in arguments)args.push(arguments[i]);
				if(ws.readyState === 1)
					ws.send(JSON.stringify(args));
				else
					console.log('连接断开，请刷新页面再试！');
			};

			fn.close = function(){
				ws.close();
			};
		}
		
		return fn;
	};

	var pix_css = function(str,name){
		name = '[' + name + ']';
		var f1 = function(str){
			var re = /([^{}]+?)\{/g;
			var match,cursor = 0,code = '',h,t,t2;
			while(match = re.exec(str)) {
				code += str.slice(cursor, match.index);
				h = match[1].split(',')
				for(var i in h){
					var v = h[i]
					v = v.trim();
					t = v.toLowerCase();
					if(t.indexOf('/deep/') !== -1){
						h[i] = v.split(/\s*\/deep\//i).join(name)
					}else if(v.lastIndexOf('::') !== -1 && v.substr(v.lastIndexOf('::')+1).indexOf(' ') === -1){
						h[i] = v.substr(0,v.lastIndexOf('::'))+name+v.substr(v.lastIndexOf('::'))
					}else if(v.lastIndexOf(':') !== -1 && v.substr(v.lastIndexOf(':')+1).indexOf(' ') === -1){
						h[i] = v.substr(0,v.lastIndexOf(':'))+name+v.substr(v.lastIndexOf(':'))
					}else{
						h[i] = v + name;
					}
				}
				code += '\n'+h.join(',\n')+'{';
				cursor = match.index + match[0].length;
			}
			code += str.slice(cursor, str.length);
			return code;
		}
		var f2 = function(str){
			var re = /(@(\w+).*)\{([\S\s]+?)\n\}/g;
			var match,cursor = 0,code = '',h,t,t2;
			var lis = {};
			while(match = re.exec(str)) {
				code += str.slice(cursor, match.index);
				var key = '<<'+Math.random()+'>>';
				switch(match[2].toLowerCase()){
					case 'media':
						lis[key] = match[1]+'{'+f1(match[3])+'}';
					break;
					default:
						lis[key] = match[0];
					break;
				}
				code += key;
				cursor = match.index + match[0].length;
			}
			code += str.slice(cursor, str.length);
			return [code,lis];
		}
		var d = f2(str);
		d[0] = f1(d[0]);
		for(var i in d[1]){
			d[0] = d[0].split(i).join(d[1][i])
		}
		return d[0];
	}

	var addcss = function(str){
		var style = document.createElement('style');
		if(style.styleSheet){
			style.styleSheet.cssText = str;
		} else {  
			style.appendChild(document.createTextNode(str));
		}
		head.appendChild(style);
		return style;
	}

	var fn,cache = {},files = [],is_babel = typeof Babel !== 'undefined';
	var load_babel = function(){
		return new Promise(function(ok){
			if(is_babel === true){
				ok();
			}else{
				if(is_babel === false){
					is_babel = [];
					var script = document.createElement('script');
					script.onload = function(){
						setTimeout(function(){
							var script = document.createElement('script');
							script.onload = function(){
								for(var i in is_babel)is_babel[i]()
								is_babel = true;
							};
							script.src= _config.lib+'babel.min.js';
							head.appendChild(script);
						})
					};
					script.src= _config.lib+'polyfill.min.js';
					head.appendChild(script);
				}
				is_babel.push(ok);
			}
		})
	}

	var get = function(url,config){
		return new Promise(function(ok,err){
			switch(config.mode){
				case 'xhr':
					var xhr = new XMLHttpRequest();
					xhr.open('GET',url + (config.debug?'?'+dec62((new Date).getTime()):''));
					xhr.onreadystatechange=function(){if(xhr.readyState==4)if(xhr.status===200)ok(xhr.responseText);else err(xhr)};
					xhr.send();
				break;
				case 'script':
					var _str = '';
					fn.callback[url] = function(str){
						_str = str;
						delete fn.callback[url];
					}
					fn.script(url+'.import?fn=xaoi.import.callback["'+url+'"]' + (config.debug?'&'+dec62((new Date).getTime()):'')).then(function(){
						ok(_str)
					})
				break;
			}
		})
	}

	var str_cutting_th1 = function(str){
		var ma = /require\s*\(\s*('|")(\S+?)\1\s*\)/gi;
		var result;
		var r = [];
		var index = 0;
		while((result = ma.exec(str)) !== null){
			r.push([str.substr(index,result.index - index),result[1],result[2]]);
			index = ma.lastIndex;
		}
		r.push([str.substr(index),'','']);
		return r;
	}

	var str_cutting_th2 = function(str){
		var ma = /import\s*\(\s*('|")(\S+?)\1\s*\)/gi;
		var result;
		var r = [];
		var index = 0;
		while((result = ma.exec(str)) !== null){
			r.push([str.substr(index,result.index - index),result[1],result[2]]);
			index = ma.lastIndex;
		}
		r.push([str.substr(index),'','']);
		return r;
	}

	var str_cutting_js = function(str){
		var ma = /import\s+('|")(\S+?)\1\s*;?/gi;
		var result;
		var r = [];
		var index = 0;
		while((result = ma.exec(str)) !== null){
			r.push([str.substr(index,result.index - index),result[2]]);
			index = ma.lastIndex;
		}
		r.push([str.substr(index),'']);
		return r;
	}

	var str_cutting_es5 = function(str){
		var ma = / = require\(['"]([^'"]+)['"]\)/gi;
		var result;
		var r = [];
		var index = 0;
		while((result = ma.exec(str)) !== null){
			r.push([str.substr(index,result.index - index),result[1]]);
			index = ma.lastIndex;
		}
		r.push([str.substr(index),'']);
		return r;
	}

	var str_cutting_es6 = function(str){
		var ma = /(import.*?\s+from\s+['"])([^'"]+)(['"])/gi;
		var result;
		var r = [];
		var index = 0;
		while((result = ma.exec(str)) !== null){
			r.push([str.substr(index,result.index - index),result[1],result[2],result[3]]);
			index = ma.lastIndex;
		}
		r.push([str.substr(index),'','','']);
		return r;
	}

	function dirname(path){
		var i = path.lastIndexOf('/')
		if(i === -1)return '/';
		return path.substr(0,i+1)
	}

	/**
	 * url转换
	 */
	var tourl = function(url,path,config){
		url = url.trim()
		if(!url.length)return '';
		if(url.indexOf('@/') === 0)url = config.root + url.substr(2)
		
		if(url.indexOf('http://') === 0 || url.indexOf('https://') === 0 || url.indexOf('/') === 0){
			
		}else{
			url = url_path(path + url);
		}

		return url
	}

	/**
	 * vue转换
	 */
	var tovue = function(str,_id){
		return new Promise(function(ok){
			
			var r = {
				template:'',
				script:'',
				style:[],
				scoped:false
			};

			if(str){
				var tmp = /<\s*(template)([^<>]*)>([\S\s]*)<\s*\/\s*\1\s*>/i.exec(str);
				if(tmp){
					r.template = tmp[3];
				}

				var match,match2,re = /<\s*(script|style)([^<>]*)>([\S\s]*?)<\s*\/\s*\1\s*>/gi,re2 = /([a-zA-Z0-9-_]+)(\s*=\s*('|")([^\3]*?)\3)?/g;
				var f = function(){
					if(match = re.exec(str)){
						var attr = {};
						while(match2 = re2.exec(match[2])){
							if(match2){
								attr[match2[1]] = match2[4]||''
							}
						}
						switch(match[1].toLowerCase()){
							case 'script':
								r.script += match[3];
								f()
							break;
							case 'style':
								var lang = attr.lang||'css';
								switch(lang){
									case 'css':
										if(typeof attr.scoped !== 'undefined'){
											r.scoped = true;
											r.style.push(pix_css(match[3],_id));
										}else{
											r.style.push(match[3]);
										}
										f()
									break;
									case 'less':
										less.render(match[3]).then(function(d){
											var css = d.css
											if(typeof attr.scoped !== 'undefined'){
												r.scoped = true;
												css = pix_css(css,_id);
											}
											r.style.push(css);
											f()
										}).catch(function(){
											f()
										})
									break;
								}
							break;
							default:
								f()
							break;
						}
					}else{
						ok(r);
					}
				}
				f()
			}else{
				ok(r);
			}
		})
	}
	
	//返回vue对象
	var vue_data = function(conf,config){
		return new Promise(function(end){
			var path = conf.path;

			new Promise(function(ok){
				if(typeof conf.data_str !== 'undefined' && conf.data_str !== false){
					ok(conf.data_str)
				}else{
					get(path,config).then(ok,function(){
						console.error('vue:'+path)
					})
				}
			}).then(function(str){
				str = fix(str,conf,config);
				return new Promise(function(ok){
					if(conf.hz === 'vue'){
						tovue(str,conf.id).then(ok)
					}else{
						ok({
							template:'',
							script:str,
							style:[],
							scoped:false
						})
					}
				})
			}).then(function(tmp){
				return new Promise(function(ok){
					if(conf.tmp && conf.tmp.link){
						for(var i in conf.tmp.link)head.removeChild(conf.tmp.link[i])
					}
		
					tmp.link = [];
					tmp.flink = [];
					if(is_es6 && !tmp.bloburl)tmp.bloburl = URL.createObjectURL(new Blob(['export default xaoi.import.cache["'+path+'"].data'],{type:'application/javascript'}))
		
					for(var i in tmp.style){
						tmp.link.push(addcss(tmp.style[i]));
					}
		
					tmp.is_reload = !conf.tmp || conf.tmp.script !== tmp.script
		
					if(tmp.script && tmp.is_reload){
						if(conf.tmp && conf.tmp.flink){
							for(var i in conf.tmp.flink)head.removeChild(conf.tmp.flink[i])
						}
					}

					ok(tmp)
				})
			}).then(function(tmp){
				//去掉注释
				return new Promise(function(ok){
					var reg = /("([^\\\"]*(\\.)?)*")|('([^\\\']*(\\.)?)*')|(\/{2,}.*?(\r|\n|$))|(\/\*(\n|.)*?\*\/)/g;
					tmp.script = tmp.script.replace(reg,function(s){return /^\/{2,}/.test(s)||/^\/\*/.test(s)?"":s});
					ok(tmp)
				})
			}).then(function(tmp){
				//import函数处理
				if(!tmp.is_reload)return tmp;
				return new Promise(function(ok){
					var lis = str_cutting_th2(tmp.script)
					tmp.code_str = '';
					var f = function(){
						var v = lis.shift()
						if(v){
							tmp.code_str += v[0]
							if(v[2])tmp.code_str += 'xaoi.import('+v[1]+tourl(v[2],dirname(path),config)+v[1]+','+config.id+')'
							f()
						}else{
							ok(tmp)
						}
					}
					f()
				})
			}).then(function(tmp){
				//require模板
				return new Promise(function(ok){
					var lis = str_cutting_th1(tmp.template)
					tmp.template = '';
					var f = function(){
						var v = lis.shift()
						if(v){
							tmp.template += v[0]
							if(v[2])tmp.template += v[1]+tourl(v[2],dirname(path),config)+v[1]
							f()
						}else{
							ok(tmp)
						}
					}
					f()
				})
			}).then(function(tmp){
				//require函数处理
				if(!tmp.is_reload)return tmp;
				return new Promise(function(ok){
					var lis = str_cutting_th1(tmp.code_str)
					tmp.code_str = '';
					var f = function(){
						var v = lis.shift()
						if(v){
							tmp.code_str += v[0]
							if(v[2])tmp.code_str += v[1]+tourl(v[2],dirname(path),config)+v[1]
							f()
						}else{
							ok(tmp)
						}
					}
					f()
				})
			}).then(function(tmp){
				//import引入处理
				if(!tmp.is_reload)return tmp;
				return new Promise(function(ok){
					var data = {}
					var lis = str_cutting_js(tmp.code_str)
					tmp.code_str = '';
					var f = function(){
						var v = lis.shift()
						if(v){
							tmp.code_str += v[0]
							v = v[1]
							if(!v){
								f();
								return;
							}
							v = tourl(v,dirname(path),config);
							var file = v.indexOf('?') !== -1?v.substr(0,v.indexOf('?') - 1):v;
							switch(file.split('.').pop().toLowerCase()){
								case 'js':
									fn.script(config.root+v).then(f,function(){
										console.error('script:'+v)
										f();
									})
								break;
								case 'css':
									fn.style(config.root+v).then(f,function(){
										console.error('style:'+v)
										f();
									})
								break;
								case 'less':
									var f6 = function(str){
										less.render(fix(str,conf)).then(function(d){
											tmp.link.push(addcss(d.css));
											f()
										}).cache(function(){
											console.error('less:'+v)
											f()
										})
									}
									get(v).then(f6,function(e){
										console.error('get:'+v)
										f()
									})
								break;
							}
						}else{
							ok(tmp)
						}
					}
					f();
				})
			}).then(function(tmp){
				if(!tmp.is_reload)return tmp;
				return new Promise(function(ok){
					if(is_es6){
						//返回blob url
						
						var code = '';
						var lis = str_cutting_es6(tmp.code_str)
	
						var f4 = function(){
							var v = lis.shift()
	
							if(v){
								code += v[0];
								if(v[2]){
									var _url = tourl(v[2],dirname(path),config);
	
									fn(_url,config.id).then(function(){
										code += v[1]
										code += cache[_url].tmp.bloburl + "#" + _url
										code += v[3]
	
										f4()
									})
								}else{
									
									f4()
								}
							}else{
								var burl = URL.createObjectURL(new Blob([code],{type:'application/javascript'}))
								new Function('str','fn','import(str).then(fn)')(burl,function(res){
									URL.revokeObjectURL(burl);
									conf.data = typeof res === 'object' && res.default?res.default:{}
	
									ok(tmp)
								})
							}
						}
						f4()
					}else{
						ok(tmp)
					}
				})
			}).then(function(tmp){
				if(!tmp.is_reload)return tmp;
				return new Promise(function(ok){
					if(is_es6){
						ok(tmp)
					}else{
						//返回对象
	
						var code = Babel.transform(tmp.code_str,{presets:['es2015','stage-2','stage-3']}).code
	
						var data = {}
						var lis = str_cutting_es5(code)
						var f4 = function(){
							var v = lis.shift()
							if(v){
								if(v[1]){
									var _url = tourl(v[1],dirname(path),config)
	
									fn(_url,config.id).then(function(){
										data[_url] = cache[_url].data
	
										f4()
									})
								}else{
									
									f4()
								}
							}else{
	
								var tmpf = new Function('exports','require',code + '\nreturn exports')
	
								var res = tmpf({},function(url){
									url = tourl(url,dirname(path),config)
									return data[url]
								})
	
								conf.data = typeof res === 'object' && res.default?res.default:{}
	
								ok(tmp)
							}
						}
						f4()
					}
				})
			}).then(function(tmp){
				if(tmp.template){
					var d = Vue.compile(tmp.template,{tostring:true});
					if(typeof d.render !== 'string'){
						var str = d.render.toString();
						d.render = str.substr(42,str.length-45);
					}
					if(!is_es6){
						d.render = Babel.transform('var __fn__ = ()=>{return '+d.render+'}',{presets:['es2015','stage-2','stage-3']}).code
						conf.data.render = new Function('with(this){var _c2 = _c;var _c = function(){var arg = [];for(var i in arguments)arg.push(arguments[i]);if(typeof arg[1] === \'undefined\')arg[1] = {};else if(Object.prototype.toString.call(arg[1]) === \'[object Array]\')arg.splice(1,0,{});if(typeof arg[1].attrs === \'undefined\')arg[1].attrs = {};arg[1].attrs["'+conf.id+'"]=\'\';return _c2.apply(this,arg)}.bind(this);'+d.render+'return __fn__()}');
					}else{
						conf.data.render = new Function('with(this){var _c2 = _c;var _c = function(){var arg = [];for(var i in arguments)arg.push(arguments[i]);if(typeof arg[1] === \'undefined\')arg[1] = {};else if(Object.prototype.toString.call(arg[1]) === \'[object Array]\')arg.splice(1,0,{});if(typeof arg[1].attrs === \'undefined\')arg[1].attrs = {};arg[1].attrs["'+conf.id+'"]=\'\';return _c2.apply(this,arg)}.bind(this);return '+d.render+'}');
					}
					conf.data.staticRenderFns = d.staticRenderFns;
				}
	
				conf.tmp = tmp
				
				end(tmp.is_reload);
			})
		})
	}

	var data_id = 1;
	var obj_config = []

	/**
	 * 入口 加载类型分离
	 * 加载js
	 * 加载vue
	 */
	fn = function(str,conf){
		if(!str)return;

		if(conf > 0){
			var id = conf
			conf = obj_config[conf-1]
		}else{
			if(conf.lib && conf.lib[conf.lib.length-1] !== '/')conf.lib += '/'
			if(conf.root && conf.root[conf.root.length-1] !== '/')conf.root += '/'
			for(var i in _config){
				if(typeof conf[i] === 'undefined')conf[i] = _config[i]
			}

			var id = obj_config.push(conf)

			conf.id = id;

			var data_str = conf.el?document.querySelector(conf.el).innerHTML.split(conf.el_script||'_script').join('script'):false

			if(conf.debug && conf.ws){
				!function(){
					var ws = _ws(conf.ws);
					var index
					ws.change = function(f){
						if(is_es6)
							console.log('%c'+f,'color:#3b9800')
						else
							console.log(f)
						f = conf.root + f.substr(1)
						if(typeof cache[f] !== 'undefined' && typeof fn.callback[f] === 'undefined'){
							cache[f].reload();
						}
					}
					ws.onopen = function(){
						index = setInterval(function(){
							ws.send('ping')
						},200*1000)
					}
					ws.onclose = function(){
						clearTimeout(index)
						setTimeout(ws,3000)
					}
					ws();
				}()
			}

			//F4
			if(conf.debug){
				document.addEventListener('keydown',function(event){
					if(event.keyCode === 115){
						event.stopPropagation();
						event.preventDefault();
						fn.reload();
					}
				});
			}
		}
		
		var path = tourl(str,conf.root,conf)
		
		return new Promise(function(ok){
			var f1 = function(){
				if(typeof cache[path] === 'undefined'){

					cache[path] = {};
					cache[path].conf = conf
					cache[path].id = 'data-v-' + data_id++;
					cache[path].hz = path.split('.').pop().toLowerCase()
					cache[path].path = path;
					cache[path].data = {};
					cache[path].reload = function(){
						switch(cache[path].hz){
							case 'vue':
								vue_data(cache[path],conf).then(function(is_reload){
									if(is_reload){
										revue.reload(path,cache[path].data)
									}else{
										revue.rerender(path,cache[path].data)
									}
								})
							break;
							case 'js':
								location.reload();
							break;
						}
					};
					cache[path].oks = [ok];
					if(data_str !== false){
						cache[path].data_str = data_str
					}
					vue_data(cache[path],conf).then(function(){
						if(cache[path].hz === 'vue')revue.createRecord(path,cache[path].data)

						for(var i in cache[path].oks)cache[path].oks[i](cache[path].data);
						cache[path].oks = true;
					})
				}else{
					if(cache[path].oks === true){
						ok(cache[path].data);
					}else{
						cache[path].oks.push(ok)
					}
				}
			}
			if(!is_es6){
				load_babel().then(f1)
			}else{
				f1()
			}
		})
	}

	fn.cache = cache

	fn.callback = {};

	fn.reload = function(){
		for(var i in cache){
			if(cache[i].hz === 'vue'){
				cache[i].reload();
			}
		}
	}

	//加载js
	fn.script = function(){
		var all = []
		for(var i in arguments){
			if(typeof arguments[i] === 'string'){
				all.push(arguments[i]);
			}else if(Object.prototype.toString.call(arguments[i]) === '[object Array]'){
				for(var j in arguments[i]){
					all.push(arguments[i][j]);
				}
			}
		}
		return Promise.all(all.map(function(url){
			return new Promise(function(ok,err){
				if(url && files.indexOf(url) === -1){
					files.push(url);
					var script = document.createElement('script');
					script.onload = function(){
						ok();
						head.removeChild(script);
					};
					script.onerror = function(e){
						err(e)
						head.removeChild(script);
					}
					script.src= url;
					head.appendChild(script);
				}else{
					ok();
				}
			});
		}));
	}

	//加载css
	fn.style = function(){
		var all = []
		for(var i in arguments){
			if(typeof arguments[i] === 'string'){
				all.push(arguments[i]);
			}else if(Object.prototype.toString.call(arguments[i]) === '[object Array]'){
				for(var j in arguments[i]){
					all.push(arguments[i][j]);
				}
			}
		}
		return Promise.all(all.map(function(url){
			return new Promise(function(ok){
				if(url && files.indexOf(url) === -1){
					files.push(url);
					var css = document.createElement("link")
					css.setAttribute("rel", "stylesheet")
					css.setAttribute("href", url)
					css.onload = ok;
					css.onerror = function(e){
						err(e)
						head.removeChild(css);
					}
					head.appendChild(css)
				}else{
					ok();
				}
			});
		}));
	}

	var fix = function(str,conf,config){
		var d = {};

		var path = conf.path.substr(0,conf.path.length - (conf.hz.length+1));

		if(path.indexOf(config.root) === 0)path = path.substr(config.root.length)

		var dir = path.split('/');
		dir.splice(-1,1);
		dir = dir.join('/')
		d.__DIR__ = config.root+dir;

		d.__NAME__ = path.split('/').join('_');

		for(var i in d){
			str = str.split(i).join(d[i]);
		}

		return str;
	}

	return fn;
}()